Creating Classes and Working with Objects in Dart
Classes and objects are essential parts of Object-Oriented Programming (OOP) in Dart.
A class provides a structure for defining data and behavior, while an object is an
actual instance created from that class. Understanding how to create classes and work
with objects is important for developing organized and reusable Dart and Flutter
applications.
JustAcademy's Flutter curriculum includes Object-Oriented Programming in Dart, including
classes, objects, and constructors, as part of its Dart Programming Fundamentals module.
The course also connects these concepts with inheritance, polymorphism, abstraction,
collections, and asynchronous programming. :contentReference[oaicite:0]{index=0}
1. What is a Class?
A class is a blueprint or template used to create objects. It defines
the properties and behaviors that objects created from the class can have.
For example, a real-world student has a name, age, roll number, and course. A
Student class can represent these characteristics in a Dart program.
Basic Class Syntax
class ClassName {
// Properties
// Methods
}
Example
class Student {
String name = "Rahul";
int age = 20;
void displayDetails() {
print("Name: $name");
print("Age: $age");
}
}
Here, Student is the class. It contains two properties,
name and age, and one method called
displayDetails().
2. What is an Object?
An object is an instance of a class. The class defines the structure,
while the object represents an actual instance of that structure.
For example:
- Class: Student
- Object: student1
- Property: name, age
- Method: displayDetails()
Creating an Object
class Student {
String name = "Rahul";
int age = 20;
void displayDetails() {
print("Name: $name");
print("Age: $age");
}
}
void main() {
Student student1 = Student();
student1.displayDetails();
}
The statement Student student1 = Student(); creates an object of the
Student class.
3. Class vs Object
| Class |
Object |
| Blueprint or template |
Instance of a class |
| Defines properties and methods |
Uses properties and methods |
| Describes what an object should contain |
Contains actual values |
Example: Student |
Example: student1 |
4. Creating a Simple Class
A class can contain properties and methods.
class Car {
String brand = "Toyota";
String color = "White";
void start() {
print("Car started");
}
}
void main() {
Car car = Car();
print(car.brand);
print(car.color);
car.start();
}
In this example, Car is the class and car is its object.
5. Creating Multiple Objects
A single class can be used to create multiple objects. Each object can contain different
values.
class Student {
String name = "";
int age = 0;
}
void main() {
Student student1 = Student();
Student student2 = Student();
student1.name = "Rahul";
student1.age = 20;
student2.name = "Priya";
student2.age = 22;
print(student1.name);
print(student1.age);
print(student2.name);
print(student2.age);
}
Both objects are created from the same class, but they store different data.
6. Properties of a Class
Properties, also called fields or instance variables, represent the data associated with
an object.
class Employee {
String name = "Amit";
int age = 25;
String department = "Development";
double salary = 50000;
}
The class contains four properties:
name
age
department
salary
7. Accessing Object Properties
The dot operator (.) is used to access properties and methods of an object.
class Employee {
String name = "Amit";
int age = 25;
}
void main() {
Employee employee = Employee();
print(employee.name);
print(employee.age);
}
Output:
Amit
25
8. Updating Object Properties
Object properties can be changed when they are not declared as final.
class Student {
String name = "Rahul";
int age = 20;
}
void main() {
Student student = Student();
student.name = "Aman";
student.age = 23;
print(student.name);
print(student.age);
}
Output:
Aman
23
9. Methods in a Class
A method is a function that is defined inside a class. Methods describe the actions or
behavior of an object.
class Calculator {
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
}
void main() {
Calculator calculator = Calculator();
print(calculator.add(10, 5));
print(calculator.subtract(10, 5));
print(calculator.multiply(10, 5));
}
10. Constructors
A constructor is used when creating an object and is commonly used to initialize its
properties.
Constructor Example
class Student {
String name;
int age;
Student(this.name, this.age);
}
void main() {
Student student = Student("Rahul", 21);
print(student.name);
print(student.age);
}
The constructor receives the values and assigns them to the object's properties.
11. Why Constructors are Useful
Constructors allow us to create objects with different values without manually assigning
every property after object creation.
class Product {
String name;
double price;
Product(this.name, this.price);
}
void main() {
Product product1 = Product("Laptop", 50000);
Product product2 = Product("Mobile", 25000);
print(product1.name);
print(product1.price);
print(product2.name);
print(product2.price);
}
12. Using the this Keyword
The this keyword refers to the current object.
class Employee {
String name;
double salary;
Employee(this.name, this.salary);
void display() {
print("Employee: $name");
print("Salary: ₹$salary");
}
}
void main() {
Employee employee = Employee("Amit", 60000);
employee.display();
}
13. Named Parameters in Constructors
Dart allows constructors to use named parameters. This can make object creation easier to
read, especially when a class contains multiple properties.
class Product {
String name;
double price;
int quantity;
Product({
required this.name,
required this.price,
required this.quantity,
});
}
void main() {
Product product = Product(
name: "Laptop",
price: 50000,
quantity: 2,
);
print(product.name);
print(product.price);
print(product.quantity);
}
14. Working with Object Methods
Once an object has been created, its methods can be called using the dot operator.
class BankAccount {
double balance = 0;
void deposit(double amount) {
balance += amount;
}
void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
}
}
void displayBalance() {
print("Balance: ₹$balance");
}
}
void main() {
BankAccount account = BankAccount();
account.deposit(10000);
account.withdraw(2500);
account.displayBalance();
}
Output:
Balance: ₹7500.0
15. Object State
The values stored inside an object represent its current state.
class Counter {
int value = 0;
void increment() {
value++;
}
}
void main() {
Counter counter = Counter();
print(counter.value);
counter.increment();
print(counter.value);
counter.increment();
print(counter.value);
}
Output:
0
1
2
16. Independent Objects
Different objects created from the same class generally maintain their own instance data.
class Counter {
int value = 0;
void increment() {
value++;
}
}
void main() {
Counter counter1 = Counter();
Counter counter2 = Counter();
counter1.increment();
counter1.increment();
counter2.increment();
print(counter1.value);
print(counter2.value);
}
Output:
2
1
The two objects maintain separate instance values.
17. Named Constructors
Dart also supports named constructors. They provide additional ways of creating objects
from a class.
class User {
String name;
int age;
User(this.name, this.age);
User.guest()
: name = "Guest",
age = 0;
}
void main() {
User user1 = User("Rahul", 25);
User user2 = User.guest();
print(user1.name);
print(user2.name);
}
18. Factory Constructors
Dart also provides factory constructors. A factory constructor can control how an object
is created and can return an existing instance or a new instance.
class User {
final String name;
User._internal(this.name);
factory User(String name) {
return User._internal(name);
}
}
void main() {
User user = User("Rahul");
print(user.name);
}
19. Final Properties
A final property can be assigned only once.
class User {
final String id;
String name;
User(this.id, this.name);
}
void main() {
User user = User("U101", "Rahul");
print(user.id);
user.name = "Aman";
print(user.name);
}
The name property can be changed, while the id property cannot
be reassigned after initialization.
20. Getters and Setters
Getters and setters allow controlled access to class properties.
class Student {
String _name = "Rahul";
String get name {
return _name;
}
set name(String value) {
_name = value;
}
}
void main() {
Student student = Student();
print(student.name);
student.name = "Aman";
print(student.name);
}
21. Private Members
In Dart, an identifier beginning with an underscore is private to its library.
This can be used to keep implementation details inside a class.
class BankAccount {
double _balance = 0;
void deposit(double amount) {
if (amount > 0) {
_balance += amount;
}
}
double getBalance() {
return _balance;
}
}
void main() {
BankAccount account = BankAccount();
account.deposit(5000);
print(account.getBalance());
}
22. Object Composition
An object can contain another object as one of its properties. This is useful when
representing relationships between real-world entities.
class Address {
String city;
String country;
Address(this.city, this.country);
}
class User {
String name;
Address address;
User(this.name, this.address);
void display() {
print("Name: $name");
print("City: ${address.city}");
print("Country: ${address.country}");
}
}
void main() {
Address address = Address("Mumbai", "India");
User user = User("Rahul", address);
user.display();
}
23. Working with Objects in Lists
Multiple objects can be stored inside a Dart List. This is particularly useful
for application data and Flutter UI lists.
class Product {
String name;
double price;
Product(this.name, this.price);
}
void main() {
List products = [
Product("Laptop", 50000),
Product("Mobile", 25000),
Product("Headphones", 3000),
];
for (Product product in products) {
print("${product.name}: ₹${product.price}");
}
}
24. Passing Objects to Functions
Objects can be passed as arguments to functions and methods.
class Student {
String name;
int marks;
Student(this.name, this.marks);
}
void displayStudent(Student student) {
print("Name: ${student.name}");
print("Marks: ${student.marks}");
}
void main() {
Student student = Student("Rahul", 85);
displayStudent(student);
}
25. Returning Objects from Functions
A function can also create and return an object.
class Product {
String name;
double price;
Product(this.name, this.price);
}
Product createProduct() {
return Product("Laptop", 50000);
}
void main() {
Product product = createProduct();
print(product.name);
print(product.price);
}
26. Practical Example: Student Management
class Student {
String name;
int rollNumber;
double marks;
Student(this.name, this.rollNumber, this.marks);
String getResult() {
if (marks >= 40) {
return "Pass";
}
return "Fail";
}
void displayDetails() {
print("Name: $name");
print("Roll Number: $rollNumber");
print("Marks: $marks");
print("Result: ${getResult()}");
}
}
void main() {
Student student1 = Student("Rahul", 101, 85);
Student student2 = Student("Priya", 102, 35);
student1.displayDetails();
print("");
student2.displayDetails();
}
27. Practical Example: E-Commerce Product
Classes and objects are especially useful for representing structured data such as
products in an e-commerce application.
class Product {
String name;
double price;
int quantity;
Product(this.name, this.price, this.quantity);
double calculateTotal() {
return price * quantity;
}
void displayProduct() {
print("Product: $name");
print("Price: ₹$price");
print("Quantity: $quantity");
print("Total: ₹${calculateTotal()}");
}
}
void main() {
Product product = Product(
"Laptop",
50000,
2,
);
product.displayProduct();
}
28. Practical Example: Employee
class Employee {
String name;
String department;
double salary;
Employee(this.name, this.department, this.salary);
void displayEmployee() {
print("Name: $name");
print("Department: $department");
print("Salary: ₹$salary");
}
}
void main() {
Employee employee1 =
Employee("Amit", "Development", 60000);
Employee employee2 =
Employee("Priya", "Testing", 55000);
employee1.displayEmployee();
print("");
employee2.displayEmployee();
}
29. Classes and Objects in Flutter
Classes and objects are fundamental to Flutter development. JustAcademy's course curriculum
introduces Dart OOP and classes, objects, and constructors before moving into Flutter
widgets and UI development. :contentReference[oaicite:1]{index=1}
Flutter widgets themselves are represented using classes. Application developers also use
classes for model objects, screens, services, controllers, repositories, and other
application components.
Flutter Widget Class Example
import 'package:flutter/material.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Home"),
),
body: const Center(
child: Text("Welcome to Flutter"),
),
);
}
}
30. Model Classes in Flutter
Model classes are commonly used to represent structured application data.
class User {
final int id;
final String name;
final String email;
User({
required this.id,
required this.name,
required this.email,
});
}
void main() {
User user = User(
id: 101,
name: "Rahul",
email: "[email protected]",
);
print(user.name);
print(user.email);
}
31. Using Objects for API Data
In Flutter applications, API responses can be converted into model objects so that the
application can work with structured Dart data.
class Product {
final int id;
final String name;
final double price;
Product({
required this.id,
required this.name,
required this.price,
});
factory Product.fromJson(Map json) {
return Product(
id: json["id"],
name: json["name"],
price: (json["price"] as num).toDouble(),
);
}
}
Here, Product represents structured product data, while
Product.fromJson() creates a product object from JSON-style data.
32. Object Lifecycle: Basic Flow
Define Class
↓
Create Object
↓
Constructor Initializes Object
↓
Object Stores Data
↓
Access Properties
↓
Call Methods
↓
Object Performs Operations
33. Advantages of Working with Classes and Objects
- Reusability: One class can be used to create multiple objects.
- Organization: Related data and behavior can be kept together.
- Maintainability: Large applications can be divided into logical classes.
- Encapsulation: Internal data can be controlled through methods and accessors.
- Scalability: Classes provide structure for larger applications.
- Real-world modeling: Real entities can be represented as objects.
- Flutter integration: Classes are widely used throughout Flutter applications.
34. Common Mistakes
Mistake 1: Defining a Class but Not Creating an Object
Defining a class does not automatically create an object.
class Student {
String name = "Rahul";
}
void main() {
Student student = Student();
print(student.name);
}
Mistake 2: Incorrect Constructor Arguments
class Student {
String name;
int age;
Student(this.name, this.age);
}
void main() {
Student student = Student("Rahul", 20);
}
Mistake 3: Trying to Modify a Final Property
class User {
final String id;
User(this.id);
}
The id property cannot be reassigned after initialization.
35. Best Practices for Creating Classes
- Use meaningful class names such as
Student, Product, and User.
- Use PascalCase for class names.
- Keep a class focused on a clear responsibility.
- Use constructors to initialize required properties.
- Use
final for values that should not be reassigned.
- Use named parameters when they make object creation clearer.
- Keep related behavior inside the appropriate class.
- Use model classes for structured application data.
- Use getters and setters when controlled property access is useful.
36. Practice Exercises
- Create a
Book class with title, author, and price properties.
- Create three different objects from the
Book class.
- Create a
Car class with brand, model, color, and price.
- Add a
start() method to the Car class.
- Create a
BankAccount class with deposit and withdrawal methods.
- Create a
Product class using named constructor parameters.
- Create a
User class with a named constructor.
- Create a list of
Product objects and display all products.
- Create a Flutter model class for a student.
- Create a Flutter widget that receives an object through its constructor.
37. Quick Revision Table
| Concept |
Purpose |
Example |
| Class |
Defines the structure of objects |
class Student {} |
| Object |
Instance of a class |
Student s = Student(); |
| Property |
Stores object data |
String name; |
| Method |
Defines object behavior |
void display() {} |
| Constructor |
Initializes an object |
Student(this.name); |
this |
Refers to the current object |
this.name |
| Getter |
Reads a property |
get name |
| Setter |
Updates a property |
set name() |
| Named Constructor |
Provides another object-creation mechanism |
User.guest() |
| Factory Constructor |
Controls object creation |
factory User() |
38. Key Takeaways
- A class is a blueprint for creating objects.
- An object is an instance of a class.
- Properties represent the data of an object.
- Methods represent the behavior of an object.
- Constructors initialize objects.
- The
this keyword refers to the current object.
- A single class can be used to create many independent objects.
- Objects can be passed to functions and returned from functions.
- Objects can be stored in collections such as lists.
- Classes and objects form an important foundation for Dart OOP and Flutter development.
39. Learn Flutter with JustAcademy
JustAcademy's Flutter training covers Dart programming and OOP concepts including classes,
objects, and constructors, followed by Flutter widgets, UI development, navigation, state
management, APIs, Firebase, projects, and other Flutter development topics. :contentReference[oaicite:2]{index=2}
Visit JustAcademy Flutter Training
Register for JustAcademy Course Demo